﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Kz.Telegram.Bot.Infrastructure.Helpers.New
{
	/// <summary>
	/// 验证辅助类（包含所有验证的正则及方法）
	/// </summary>
	public class ValidateHelper
	{
		#region 验证方法
		/// <summary>
		/// 验证条件是否为真，不为真时抛出ValidateException验证异常
		/// </summary>
		/// <param name="condition">条件</param>
		/// <param name="userMessage">当condition不为真时需要抛出的异常中的消息</param>
		public static void IsTrue(bool condition, String userMessage)
		{
			if (!condition)
			{
				throw new ValidateException(userMessage);
			}
		}

		/// <summary>
		/// 验证不为null，为null时抛出ValidateException验证异常
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="userMessage"></param>
		public static void IsNotNull(object obj, String userMessage)
		{
			IsTrue(obj != null, userMessage);
		}

		/// <summary>
		/// 验证不为null且不为空字符串，为null时抛出ValidateException验证异常
		/// </summary>
		/// <param name="str"></param>
		/// <param name="userMessage"></param>
		public static void IsNotNullAndEmpty(string str, String userMessage)
		{
			IsTrue(!string.IsNullOrEmpty(str), userMessage);
		}

		/// <summary>
		/// 验证不为null且不为空白字符串，为null时抛出ValidateException验证异常
		/// </summary>
		/// <param name="str"></param>
		/// <param name="userMessage"></param>
		public static void IsNotNullAndWhiteSpace(string str, String userMessage)
		{
			IsTrue(!string.IsNullOrWhiteSpace(str), userMessage);
		}
		#endregion

		#region 是否为有效的小数位数精度
		/// <summary>
		/// 是否为有效的小数位数精度
		/// </summary>
		/// <param name="d">数字</param>
		/// <param name="digits">最大允许的小数位数</param>
		/// <param name="userMessage">当验证不通过时需要抛出的异常消息</param>
		public static void IsCorrect_DecimalDigits(decimal d, int digits, String userMessage)
		{
			ValidateHelper.IsTrue(IsCorrect_DecimalDigits(d, digits), userMessage);
		}

		/// <summary>
		/// 是否为有效的小数位数精度
		/// </summary>
		/// <param name="d">数字</param>
		/// <param name="digits">最大允许的小数位数</param>
		/// <returns>是否验证通过</returns>
		public static bool IsCorrect_DecimalDigits(decimal d, int digits)
		{
			return d == Math.Round(d, digits, MidpointRounding.AwayFromZero);
		}
		#endregion
	}

	/// <summary>
	/// 验证异常类
	/// </summary>
	[Serializable]
	public class ValidateException : ApplicationException
	{
		/// <summary>
		/// 带参构造
		/// </summary>
		/// <param name="msg">错误消息</param>
		public ValidateException(string msg) : base(msg) { }
	}
}
